package com.dxd.onlineshop.service;

import com.dxd.onlineshop.mapper.SystemSettingMapper;
import com.dxd.onlineshop.pojo.SystemSetting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SystemSettingService {

    @Autowired
    private SystemSettingMapper systemSettingMapper;

    //获取所有设置
    public Map<String, Object> getAllSettings() {
        List<SystemSetting> settings = systemSettingMapper.getAllSettings();
        Map<String, Object> settingsMap = new HashMap<>();
        for (SystemSetting setting : settings) {
            settingsMap.put(setting.getKey(), convertValue(setting.getValue(), setting.getType()));
        }
        return settingsMap;
    }

    //更新设置
    public void updateSettings(Map<String, Object> settings) {
        for (Map.Entry<String, Object> entry : settings.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            String type = getValueType(value);

            SystemSetting existingSetting = systemSettingMapper.getSettingByKey(key);
            if (existingSetting == null) {
                SystemSetting newSetting = SystemSetting.builder()
                        .key(key)
                        .value(value.toString())
                        .type(type)
                        .build();
                systemSettingMapper.insertSetting(newSetting);
            } else {
                existingSetting.setValue(value.toString());
                existingSetting.setType(type);
                systemSettingMapper.updateSetting(existingSetting);
            }
        }
    }

    private Object convertValue(String value, String type) {
        switch (type) {
            case "boolean":
                return Boolean.parseBoolean(value);
            case "int":
                return Integer.parseInt(value);
            case "double":
                return Double.parseDouble(value);
            default:
                return value;
        }
    }

    private String getValueType(Object value) {
        if (value instanceof Boolean) return "boolean";
        if (value instanceof Integer) return "int";
        if (value instanceof Double) return "double";
        return "string";
    }
}